package com.gqs.bookstore.web.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.gqs.bookstore.dao.BookDao;
import com.gqs.bookstore.dao.impl.BookDaoImpl;
import com.gqs.bookstore.util.Constants;
import com.gqs.bookstore.vo.Book;
import com.gqs.bookstore.vo.Goods;
import com.gqs.bookstore.vo.ShopCart;

@SuppressWarnings("serial")
@WebServlet("/cart.do")
public class ShopCartServlet extends BaseServlet {
	private BookDao bookDao = new BookDaoImpl();
	
	/**
	 *	/cart.do?m=add&id=XXX
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @throws SQLException 
	 */
	public void addCart(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException, SQLException {
		String bId = request.getParameter("bId");
//		Long id = Long.parseLong(bId);
//		Goods goods = new Book();
//		goods = bookDao.findById(id);
		Goods goods = new Book();//这里goods用的是下转型，所以goods拥有book对象所有的属性
		goods = bookDao.findById(Long.valueOf(bId));
		
		HttpSession session = request.getSession();
		//在第二次买东西时【不管买的是否是同类商品】；因为session可在多个页面即一次会话中传递数据
		ShopCart cart = (ShopCart) session.getAttribute("cart");
		if(cart==null){//第一次买东西时
			cart = new ShopCart();
			session.setAttribute("cart", cart);
		}
		cart.addItem(goods);//第二次购买某类相同的货物，count的值已经加1
		response.sendRedirect("cart.do?m=showCart");
	}
	
	public void showCart(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		RequestDispatcher dispatcher = request.getRequestDispatcher(Constants.JSP_PATH+"my_cart.jsp");
		dispatcher.forward(request, response);
	}
}
